package com.jeason.fileserver.service.impl;

import com.jeason.fileserver.entity.FileBean;
import com.jeason.fileserver.dao.FileDao;
import com.jeason.fileserver.service.FileService;
import com.jeason.fileserver.utils.FileConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * (File)表服务实现类
 *
 * @author makejava
 * @since 2021-01-17 13:41:03
 */
@Service("fileService")
public class FileServiceImpl implements FileService {
    @Resource
    private FileDao fileDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public FileBean queryById(Integer id) {
        return this.fileDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<FileBean> queryAllByLimit(int offset, int limit) {
        return this.fileDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param fileBean 实例对象
     * @return 实例对象
     */
    @Override
    public FileBean insert(FileBean fileBean) {
        this.fileDao.insertSelective(fileBean);
        return fileBean;
    }

    /**
     * 修改数据
     *
     * @param fileBean 实例对象
     * @return 实例对象
     */
    @Override
    public FileBean update(FileBean fileBean) {
        this.fileDao.update(fileBean);
        return this.queryById(fileBean.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.fileDao.deleteById(id) > 0;
    }

    @Override
    public List<FileBean> searchByKeyword(String keyword) {
        return this.fileDao.searchByKeyword(keyword);
    }

    @Override
    public List<FileBean> searchByTime(Date beginTime, Date endTime) {
        return this.fileDao.searchByTime(beginTime, endTime);
    }

    @Override
    public String updateFileName(String name, String imgUrl) {
        List<FileBean> list = fileDao.queryByFilePath(imgUrl);
        if (list.size() < 1){
            throw new RuntimeException("该文件不存在");
        }
        FileBean fileBean = new FileBean();
        fileBean.setId(list.get(0).getId());
        fileBean.setFileName(name);
        if (fileDao.update(fileBean) < 1){
            throw new RuntimeException("修改名称失败");
        }
        return name;
    }

    @Override
    public int deleteFileById(Integer id) {
        FileBean fileBean = fileDao.queryById(id);
        File file = new File(FileConfig.getProfile() + fileBean.getFilePath());
        if (file.exists()) {
            file.delete();
            System.out.println("===========删除成功=================");
        } else {
            System.out.println("===============删除失败==============");
            throw new RuntimeException("删除失败");
        }

        return fileDao.deleteById(id);
    }

    @Override
    public boolean downloadFileById(HttpServletResponse response, Integer id) {
        FileBean fileBean = fileDao.queryById(id);
        String filePath = fileBean.getFilePath();
        String fileName = fileBean.getFileName();
        if (filePath != null) {
            //设置文件路径
            File file = new File(FileConfig.getProfile() + filePath);
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                // 设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return false;
    }
}
